package fr.ssd.jvc;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JavaVersionChecker {

	protected Map<String, String> javaVersion = new HashMap<String, String>();

	public JavaVersionChecker() {
		javaVersion.put("45.3", "1.0 or 1.1");
		javaVersion.put("46.0", "1.2");
		javaVersion.put("47.0", "1.3");
		javaVersion.put("48.0", "1.4");
		javaVersion.put("49.0", "1.5");
		javaVersion.put("50.0", "1.6");
	}

	public static void main(String[] args) throws IOException {
		if (args.length == 1) {
			new JavaVersionChecker().checkAllClassVersion(args[0].split(":"));
		} else {
			System.out.println("usage : mvm -Prun -Dfiles=<file1>:<file2>");
		}
	}

	public void checkAllClassVersion(String[] filenames) throws IOException {
		for (int i = 0; i < filenames.length; i++) {

			System.out.println(checkClassVersion(filenames[i]));
		}
	}

	public String checkClassVersion(String filename) throws IOException {
		DataInputStream in = new DataInputStream(new FileInputStream(filename));
		return checkClassVersion(in);
	}

	public String checkClassVersion(DataInputStream in) throws IOException {
		StringBuilder sb = new StringBuilder();
		int magic = in.readInt();
		if (magic != 0xcafebabe) {
			sb.append("not a valid class!");
		} else {
			int minor = in.readUnsignedShort();
			int major = in.readUnsignedShort();
			String version = javaVersion.get(major + "." + minor);
			sb.append(major);
			sb.append(".");
			sb.append(minor);
			sb.append(" - java version ");
			sb.append(version);
			in.close();
		}
		return sb.toString();
	}
}
